package demo4;

import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Set;

public class SmallestK {

    public int[] smallestK(int[] arr, int k) {
        if(k >= arr.length) {
            return arr;
        }
        if(k <= 0) {
            return new int[]{};
        }
        PriorityQueue<Integer> queue = new PriorityQueue<>(((o1, o2) -> o2.compareTo(o1)));
        for (int i = 0; i < arr.length; i++) {
            if(queue.size() < k) {
                queue.offer(arr[i]);
            } else {
                Integer peek = queue.peek();
                if(peek > arr[i]) {
                    queue.poll();
                    queue.offer(arr[i]);
                }
            }
        }
        int[] ret = new int[queue.size()];
        int i = 0;
        for(int num : queue) {
            ret[i++] = num;
        }
        return ret;
    }
}
